﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Program10
{
    /// <summary>
    /// 加密类
    /// </summary>
    public class Encryption
    {
        //盐，模拟，实际情况由随机算法按每用户标识生成
        private static readonly byte[] SaltKeys =
        {
            0xfa, 0x5e, 0x65, 0x05, 0xaf, 0x77, 0xfe, 0x45, 0x95, 0xa0, 0x18, 0x65, 0x20, 0x65, 0x32, 0xff
        };

        /// <summary>
        /// 用md5一次加密，然后加盐后，用sha512二次加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetEncryptString(string str)
        {
            var md5 = MD5.Create();
            var sha512 = SHA512.Create();

            //将字符转换成二进制数组
            var bitArray = Encoding.GetEncoding("UTF-8").GetBytes(str);

            //进行二次加密
            var encryptArray = sha512.ComputeHash(md5.ComputeHash(bitArray).Concat(SaltKeys).ToArray());

            var encryptStr = "";
            for (var i = 0; i < encryptArray.Length; i++)
            {
                encryptStr += encryptArray[i].ToString("x2");
            }
            md5.Clear();
            sha512.Clear();

            return encryptStr;
        }

        //public static string GetSHA(string str)
        //{
        //    var sha = SHA512.Create();
        //    //将字符转换成二进制数组
        //    var bitArray = Encoding.GetEncoding("UTF-8").GetBytes(str);
        //    //进行加密
        //    var md5BitArray = sha.ComputeHash(bitArray);

        //    var encryptStr = "";
        //    for (var i = 0; i < md5BitArray.Length; i++)
        //    {
        //        encryptStr += md5BitArray[i].ToString("x2");
        //    }
        //    sha.Clear();
        //    return encryptStr;
        //}
    }
}